<template>
  <div>
    <h1>电池管理</h1>
    <!---搜索表单-->
    <div class="search-div">
      <el-form label-width="70px" size="small">
        <el-row>
          <el-col :span="15">
            <el-form-item label="地点">
              <el-select
                  v-model="form.province"
                  placeholder="省"
                  size="large"
                  style="width: 200px;"
                  @change="getCityList(form.province)"
              >
                <el-option
                    v-for="item in provinceList"
                    :key="item"
                    :label="item"
                    :value="item"
                />
              </el-select>
              <el-select v-model="form.city" placeholder="市" style="width: 200px" @change="getDistrictList(form.city)">
                <el-option
                    v-for="item in cityList"
                    :key="item"
                    :label="item"
                    :value="item"
                />
              </el-select>
              <el-select v-model="form.district" placeholder="市" style="width: 200px">
                <el-option
                    v-for="item in districtList"
                    :key="item"
                    :label="item"
                    :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间">
              <el-date-picker
                  v-model="createTimes"
                  type="datetimerange"
                  range-separator="To"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="display:flex">
          <el-button type="primary" size="small" @click="searchSysUser">
            搜索
          </el-button>
          <el-button size="small" @click="resetData">重置</el-button>
            <el-button size="small" type="success" @click="overdueBattery">禁用列表</el-button>
            <el-button size="small" type="success" @click="enableBattery">启用列表</el-button>
             <el-button size="small" type="success"  @click="addbaidu">添加信息</el-button>
        </el-row>
      </el-form>
    </div>

    <!---数据表格-->
    <el-table :data="list" style="width: 100%">
      <el-table-column prop="province" label="省" />
      <el-table-column prop="city" label="市" />
      <el-table-column prop="district" label="区" />
      <el-table-column prop="createtime" label="开始时间" />
      <el-table-column prop="description" label="描述" />
      <el-table-column prop="sixty" label="60数量" />
      <el-table-column prop="fortyFive" label="45数量" />
      <el-table-column prop="maxSixty" label="最大60数量" />
      <el-table-column prop="maxFortyFive" label="最大45数量" />
      <el-table-column label="操作" align="center" width="280" #default="scope">
        <el-button type="danger" size="small" @click="updateById(scope.row)">
          {{ scope.row.state == 0 ? '禁用' : '启用' }}
        </el-button>
        <el-button type="danger" v-show="scope.row.state===1" size="small" @click="deleteById(scope.row)">
          删除
        </el-button>
      </el-table-column>
    </el-table>

    <!--分页条-->
    <el-pagination
        v-model:current-page="pageParamsList.page"
        v-model:page-size="pageParamsList.limit"
        :page-sizes="[2, 20, 50, 100]"
        @size-change="fetchSysUser"
        @current-change="fetchSysUser"
        layout="total, sizes, prev, pager, next"
        :total="total"
    />
    <el-dialog v-model="dialogVisible" title="添加站点">
      <el-form :model="formMapRef" label-width="100px">

     <el-form-item>
       <baidu-map
           style="display:flex;flex-direction: column-reverse;"
           class="map-container"
           @ready="handleAddressResult"
           ak="K9LhQIqZNlDZceYvgT6OZdxRD8K3Rxhm" v="3.0" type="API"
           :map-click="true"
           :scroll-wheel-zoom="true"
           :center="{lng: 116.404, lat: 39.915}" :zoom="15"
       >
         <div style="display:flex;justify-content:center;margin:15px">
               <bm-marker :position="{lng: formMapRef.longitude, lat: formMapRef.latitude}" :dragging="true" animation="BMAP_ANIMATION_BOUNCE"></bm-marker>
         </div>
         <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation="true" @address-result="handleAddressResult"></bm-geolocation>
       </baidu-map>
     </el-form-item>
        <el-form-item label="归属地址：" prop="building">
              <el-input v-model="formMapRef.building" readonly="readonly" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="经度：">
          <el-input v-model="formMapRef.longitude" readonly="readonly" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="维度：">
          <el-input v-model="formMapRef.latitude" readonly="readonly" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
                 <div class="dialog-footer">
                   <el-button @click="dialogVisible = false">取消</el-button>
                   <el-button type="primary" @click="addBattery">
                     确定
                   </el-button>
                 </div>
               </template>
    </el-dialog>
  </div>
</template>

<script setup>

//开始和结束时间数据模型
import {onMounted, ref} from "vue";
import {
  CityList,
  DistrictList,
  FindCategoryByParentId, getAddBattery,
  getBatteryList,
  getDeleteBattery,
  getUpdateState
} from "@/api/changebattery/battery";
import {ElMessage, ElMessageBox} from "element-plus";
import {
  BaiduMap, BmGeolocation, BmMarker
  //百度逆地址解析
  // BmGeolocation
} from 'vue-baidu-map-3x';


const map=ref(null)

//获取经纬度
const handleAddressResult = ({BMap, map}) => {
  map.value = map
  map.addEventListener('click', (e) => {
    // alert(e.point.lng + "," + e.point.lat)
    //进行获取地址
    const geocoder = new BMap.Geocoder()
    geocoder.getLocation(new BMap.Point(e.point.lng,e.point.lat), (res) => {
      formMapRef.value.building = res.address
      formMapRef.value.longitude = e.point.lng
      formMapRef.value.latitude = e.point.lat
      formMapRef.value.province=res.addressComponents.province
      formMapRef.value.city=res.addressComponents.city
      formMapRef.value.district=res.addressComponents.district
      formMapRef.value.description=res.addressComponents.street+res.addressComponents.streetNumber
    })
  })
}

//添加
const addBattery=async ()=>{
  const {code} = await  getAddBattery(formMapRef.value);
  if(code===200){
    ElMessage.success("添加成功")
    dialogVisible.value=false
    await fetchSysUser()
  }else{
    ElMessage.error("添加失败")
  }

}





// // 表单
const formMap={
  building:'',
  longitude:'',
  latitude:'',
  description:'',
  searchJingwei:'',
  //省
  province:'',
  //市
  city:'',
  //区线号
  district:'',
}

const formMapRef=ref(formMap)







const addbaidu=() =>{
  // 打开表单
  dialogVisible.value = true
}

const createTimes = ref([])

const list = ref([])
//
const dialogVisible = ref(false);

//区
const getDistrictList = async () =>{
  const {data} = await DistrictList(form.value.city)
  districtList.value=data
}

//市
const getCityList =async () =>{
  const {data} = await CityList(form.value.province);
  cityList.value=data
}

//启用用户
const enableBattery = () =>{
  form.value.state=0
  fetchSysUser()
}
//否用用户
const overdueBattery = () =>{
  form.value.state=1
  fetchSysUser()
}

const queryDto = {
  province: '',
  city: '',
  createTimeBegin: '',
  createTimeEnd: '',
  district:'',
  state:0
}

//省
const provinceList=ref([])

//市
const cityList=ref([])

//区
const districtList=ref([])


const form = ref(queryDto)


// 删除数据
const deleteById = row => {
  ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const { code } = await getDeleteBattery(row.id)
    if (code === 200) {
      ElMessage.success('删除成功')
      pageParamsUsers.value.page = 1
      await fetchSysUser()
    }
  })
}

//重置
const resetData = async () => {
  form.value.city=''
  form.value.district=''
  form.value.createTimeEnd=''
  form.value.createTimeBegin=''
  form.value.province=''
  createTimes.value=[]
  await fetchSysUser()
}

//停用启用
//上架下架
const updateById = async (row) => {
  const { code } = await getUpdateState(row.aid)
  ElMessage.success('操作成功')
  await fetchSysUser(pageParamsUsers.value.page,
      pageParamsUsers.value.limit,
      form.value)
}

//搜索方法
const searchSysUser = () => {
  fetchSysUser(
      pageParamsUsers.value.page,
      pageParamsUsers.value.limit,
      form.value
  )
}


//省
const getProvinceList = async () => {
  const {data} = await FindCategoryByParentId();
  provinceList.value = data;
}

//列表
const fetchSysUser = async () => {
  //获取开始和结束时间
  if (createTimes.value.length == 2) {
    form.value.createTimeBegin = createTimes.value[0]
    form.value.createTimeEnd = createTimes.value[1]
  }
  const { data } = await getBatteryList(
      pageParamsUsers.value.page,
      pageParamsUsers.value.limit,
      form.value
  )
  list.value = data.records
  total.value = data.total
}
onMounted(async ()=>{
  fetchSysUser()
  getProvinceList()
})
//分页数据
const pageParamsList = {
  page: 1,
  limit: 10,
}
const total = ref(0)
const pageParamsUsers = ref(pageParamsList)

</script>

<style lang="scss" scoped>
.map-container {
  //去除百度地图的图标
  ::v-deep .anchorBL {
    display: none !important;
  }
}

.map-container {
  width: 100%;
  height: 400px;
}
#allmap{
  height: 450px;
  width: 100%;
  margin: 10px 0;
}
</style>
